package com.zq.order.service.impl;

import cn.hutool.system.UserInfo;
import com.alibaba.fastjson.JSON;
import com.zq.api.cart.CartFeignClient;
import com.zq.api.product.ProductFeignClient;
import com.zq.api.user.UserFeignClient;
import com.zq.common.exception.ResultException;
import com.zq.common.util.JwtUtil;
import com.zq.common.util.Result;
import com.zq.order.dao.dto.OrderInfoDto;
import com.zq.order.dao.entity.*;
import com.zq.order.dao.vo.TradeVo;
import com.zq.order.mapper.OrderInfoMapper;
import com.zq.order.mapper.OrderItemMapper;
import com.zq.order.mapper.OrderLogMapper;
import com.zq.order.service.IOrderItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单项信息 服务实现类
 * </p>
 *
 * @author 张乔
 * @since 2025-05-20
 */
@Service
@Slf4j
public class OrderItemServiceImpl extends ServiceImpl<OrderItemMapper, OrderItem> implements IOrderItemService {
    @Resource
    private CartFeignClient cartFeignClient;

    //    用户确认下单
    @Override
    public TradeVo getTrade(String token) {
        Object data = cartFeignClient.getAllChecked(token).getData();
        List<CartInfo> cartInfoList =
                JSON.parseArray(JSON.toJSONString(data), CartInfo.class);
        List<OrderItem> orderItemList = new ArrayList<>();
        for (CartInfo cartInfo : cartInfoList) {        // 将购物项数据转换成功订单明细数据
            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(cartInfo.getSkuId());
            orderItem.setSkuName(cartInfo.getSkuName());
            orderItem.setSkuNum(cartInfo.getSkuNum());
            orderItem.setSkuPrice(cartInfo.getCartPrice());
            orderItem.setThumbImg(cartInfo.getImgUrl());
            orderItemList.add(orderItem);
        }

        // 计算总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for(OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.
                    add(orderItem.getSkuPrice()
                            .multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);

        return tradeVo;
    }


    //    根据订单id查询订单信息
    @Override
    public TradeVo getTradeByOrderId(String token, Long orderId) {
        Object data = cartFeignClient.getByOrderId(orderId).getData();
        CartInfo cartInfo = JSON.parseObject(JSON.toJSONString(data), CartInfo.class);
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(cartInfo.getSkuId());
        orderItem.setSkuName(cartInfo.getSkuName());
        orderItem.setSkuNum(cartInfo.getSkuNum());
        orderItem.setSkuPrice(cartInfo.getCartPrice());
        orderItem.setThumbImg(cartInfo.getImgUrl());
        // 计算总金额
        BigDecimal totalAmount = new BigDecimal(0);
        List<OrderItem> orderItemList = new ArrayList<>();
        orderItemList.add(orderItem);
        for(OrderItem orderItemmm : orderItemList) {
            totalAmount = totalAmount.
                    add(orderItem.getSkuPrice()
                            .multiply(new BigDecimal(orderItemmm.getSkuNum())));
        }
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }
    //    根据商品id查询订单信息

    @Resource
    private ProductFeignClient productFeignClient;
    @Override
    public TradeVo getTradeBySkuId(String token, Long skuId) {

        Object data = productFeignClient.getBySkuId(skuId).getData();
        OrderItem orderItem = new OrderItem();
        ProductSku productSku = JSON.parseObject(JSON.toJSONString(data), ProductSku.class);
        orderItem.setSkuId(productSku.getId());
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setSkuNum(1);
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setThumbImg(productSku.getThumbImg());
        // 计算总金额
        BigDecimal totalAmount = new BigDecimal(0);

        List<OrderItem> orderItemList = new ArrayList<>();
        orderItemList.add(orderItem);
        for(OrderItem orderItemmm : orderItemList) {
            totalAmount = totalAmount.
                    add(orderItem.getSkuPrice()
                            .multiply(new BigDecimal(orderItemmm.getSkuNum())));
        }
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }

    @Override
    public TradeVo getALlCart(String token) {

        Object data = cartFeignClient.getAllCkeckedcart(token).getData();

        List<CartInfo> cartInfoList =
                JSON.parseArray(JSON.toJSONString(data), CartInfo.class);
        List<OrderItem> orderItemList = new ArrayList<>();
        for (CartInfo cartInfo : cartInfoList) {        // 将购物项数据转换成功订单明细数据
            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(cartInfo.getSkuId());
            orderItem.setSkuName(cartInfo.getSkuName());
            orderItem.setSkuNum(cartInfo.getSkuNum());
            orderItem.setSkuPrice(cartInfo.getCartPrice());
            orderItem.setThumbImg(cartInfo.getImgUrl());
            orderItemList.add(orderItem);
        }

        // 计算总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for(OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.
                    add(orderItem.getSkuPrice()
                            .multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);

        return tradeVo;
    }

    @Resource
    private UserFeignClient userFeignClient;

@Resource
private OrderInfoMapper orderInfoMapper;

@Resource
private OrderItemMapper orderItemMapper;

@Resource
private OrderLogMapper orderLogMapper;


    //生成订单
    @Override
    public Long createOrder(String token, OrderInfoDto orderInfoDto) {
        // 数据校验
        List<OrderItem> orderItemList = orderInfoDto.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList)) {
            throw new ResultException(500,"数据异常");
        }
        for (OrderItem orderItem : orderItemList) {
           Object data = productFeignClient.getBySkuId(orderItem.getSkuId()).getData();
            ProductSku productSku = JSON.parseObject(JSON.toJSONString(data), ProductSku.class);
            if(null == productSku) {
                throw new ResultException(500,"数据异常");
            }
            //校验库存
            if(orderItem.getSkuNum() > productSku.getStockNum()) {
                throw new ResultException(500,"库存不够啊！");
            }
        }

        Object userInfo = userFeignClient.getUserInfo(token).getData();
        User user = JSON.parseObject(JSON.toJSONString(userInfo), User.class);
        if (null == user) {
            throw new ResultException(500,"用户不存在");
        }
        OrderInfo orderInfo = new OrderInfo();
        //订单编号
        orderInfo.setOrderNo(String.valueOf(System.currentTimeMillis()));
        log.info("订单编号："+orderInfo.getOrderNo());
        log.info("用户id："+user);
orderInfo.setUserId(Long.valueOf(user.getId()));
        //用户收货地址信息
        Object userAddressdata = userFeignClient.
                getById(Math.toIntExact(orderInfoDto.getUserAddressId())).getData();
        UserAddress userAddress = JSON.parseObject(JSON.toJSONString(userAddressdata), UserAddress.class);
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
//        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
//        orderInfo.setReceiverCity(userAddress.getCityCode());
//        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setRemark(orderInfoDto.getRemark());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());
        //订单金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount);
orderInfo.setNickName(user.getUsername());
        orderInfo.setPayType(2);
        orderInfo.setOrderStatus(0);
        orderInfoMapper.insert(orderInfo);

        //保存订单明细
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        }

        //记录日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLogMapper.insert(orderLog);


cartFeignClient.deleteChecked(token);
        return orderInfo.getId();


    }


    //修改订单状态
    @Override
    public void updateOrderType(String token, Long orderId, String paymentType) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (null == orderInfo) {
            throw new ResultException(500,"订单不存在");
        }
        orderInfo.setOrderStatus(1);
        orderInfo.setPaymentTime(LocalDateTime.now());
        orderInfo.setPayType(1);
    }


}
